#!/usr/bin/env python3
import socket
import struct
import os

RESPONSE_FILES = [ "archive.tar", "log1","log2"]  # The file server will send back

import argparse

def main():
    parser = argparse.ArgumentParser(description="Process an archive file and reply to the client with an archive and log files ")
    parser.add_argument("--cachedir", required=True, help="Path to the input/output files")
    parser.add_argument("--ip", required=True, help="IP address to append")
    parser.add_argument("--port", required=True, help="IP address to append")
    args = parser.parse_args()
    print(args)

    host = args.ip
    port = int(args.port)
    cachedir = args.cachedir

    while 1:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
            server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            server_socket.bind((host, port))
            server_socket.listen()
            print(f"Server listening on {host}:{port}...")

            conn, addr = server_socket.accept()
            with conn:
                print(f"Connected by {addr}")
                # Receive Command 
                command = conn.recv(8)
                command = struct.unpack("!Q", command)[0]

                if command == 1:
                    # Receive file size
                    file_size_data = conn.recv(8)
                    file_size = struct.unpack("!Q", file_size_data)[0]
                    print(f"File size: {file_size} bytes")

                    # Receive file data
                    with open(cachedir+"/archivereceived.tar", "wb") as file:
                        received = 0
                        while received < file_size:
                            chunk = conn.recv(1024)
                            if not chunk:
                                break
                            file.write(chunk)
                            received += len(chunk)

                        print(f"File {cachedir+"/tmp"} received successfully!")

                        print("All files received successfully.")
                if command == 2:
                    for RESPONSE_FILE in RESPONSE_FILES:
                        # Now send back a response file to the client
                        if os.path.exists(RESPONSE_FILE):
                            response_file_size = os.path.getsize(RESPONSE_FILE)

                            # Send file size
                            conn.sendall(struct.pack("!Q", response_file_size))

                            # Send file data
                            with open(RESPONSE_FILE, "rb") as file:
                                while chunk := file.read(1024):
                                    conn.sendall(chunk)

                            print(f"Response file {RESPONSE_FILE} sent successfully!")
                        else:
                            print(f"Response file {RESPONSE_FILE} not found! No response sent.")

                print("Connection closed.")
if __name__ == "__main__":
    main()    
    
